package com.hdd.utils.wxUtils;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 
 * @ClassName: XmlParser
 * @Description: Xml解析生成
 * @author yangjian
 
 *
 */
public class WeiXinPayXmlParser {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(WeiXinPayXmlParser.class);

    public static String requestToString(HttpServletRequest request){
        String resultXml = null;
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            resultXml = new String(outSteam.toByteArray(), StandardCharsets.UTF_8);
            inStream.close();
            outSteam.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultXml;

    }

    //对象转XML
    public static String BeanToXml(Object object) {
        try {
            StringBuffer sb = new StringBuffer();
            sb.append("<xml>");
            Class clazz = object.getClass();
            Method[] methods =  clazz.getDeclaredMethods();
            for (Method method : methods) {
               String methodName = method.getName();
               if(methodName.startsWith("get")){//获取get方法
                   Object value = method.invoke(object, null);
                   if(value!=null){
                       String fieldName = methodName.substring(3, methodName.length()).toLowerCase();
                       sb.append("<"+fieldName+">"+value.toString()+"</"+fieldName+">");
                   }        
               }
            }
            Class superClazz = clazz.getSuperclass();
            if(!superClazz.getName().equals("java.lang.Object")){
                Method[] superMethods =  superClazz.getDeclaredMethods();
                for (Method method : superMethods) {
                    String methodName = method.getName();
                    if(methodName.startsWith("get")){//获取get方法
                        Object value = method.invoke(object, null);
                        if(value!=null){
                            String fieldName = methodName.substring(3, methodName.length()).toLowerCase();
                            sb.append("<"+fieldName+">"+value.toString()+"</"+fieldName+">");
                        }        
                    }
                 }
            }
            sb.append("</xml>");
            return sb.toString();
        } catch (Exception e) {
            LOGGER.error("XmlParser.beanToXml error:{}", e);
        }
        return null;
    }
    //xml转对象
    public static <T> T XmlToBean(String xml,Class<T> clazz){
        try {
            if (StringUtils.isEmpty(xml))
                return null;
            // 将字符串转化为XML文档对象
            Document document = DocumentHelper.parseText(xml);
            // 获得文档的根节点
            Element root = document.getRootElement();
            // 遍历根节点下所有子节点
            Iterator<?> iter = root.elementIterator();   
            // 遍历所有结点,利用反射机制，调用set方法
            // 获取该实体的元类型
            T obj = clazz.newInstance();//创建这个实体的对象             
            while(iter.hasNext()){
                Element ele = (Element)iter.next();
                //获取字段属性
                Field field = null;
                Method method = null;
                String fiedName = ele.getName();
                //父类字段判断
                if(fiedName.equals("appid") || fiedName.equals("mch_id") || fiedName.equals("nonce_str") || fiedName.equals("sign")){
                    field =  clazz.getSuperclass().getDeclaredField(ele.getName());
                    //获取方法
                    try{
                        fiedName = fiedName.substring(0, 1).toUpperCase()+fiedName.substring(1, fiedName.length());
                        method = clazz.getSuperclass().getDeclaredMethod("set"+fiedName, field.getType());
                    }catch(NoSuchMethodException e){
                        LOGGER.warn("set"+ele.getName()+"方法不存在");
                        continue;
                    }               
                   
                }else{
                    field = clazz.getDeclaredField(ele.getName());
                  //获取方法
                    try{
                        fiedName = fiedName.substring(0, 1).toUpperCase()+fiedName.substring(1, fiedName.length());
                        method = clazz.getDeclaredMethod("set"+fiedName, field.getType());
                    }catch(NoSuchMethodException e){
                        LOGGER.warn("set"+ele.getName()+"方法不存在");
                        continue;
                    }               
                }
                //调用set方法               
                if(field.getType().getName().equals("java.lang.Long")){
                    method.invoke(obj, Long.valueOf(ele.getText()));
                }else if(field.getType().getName().equals("double")){
                    method.invoke(obj, Double.valueOf(ele.getText()).doubleValue());
                }else{
                    method.invoke(obj, ele.getText());
                } 
            }
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("xml 格式异常: ",e);
        }
        return null;
    }
    
    /**
     * xml string convert to mao object
     * @param str
     */
    public static Map<String, Object> xmlFormatStringToMap(String str) {
        if (!StringUtils.isEmpty(str)) {
            try {
                Element root = DocumentHelper.parseText(str).getRootElement();
 
                // 获取所有子节点
                List<Element> elements = root.elements();
                Map<String, Object> result = null;
                for (Element element : elements) {
                    // 第一次进入初始化
                    if (result == null){
                        result = new HashMap<>();
                    }
                    result.put(element.getName(), element.getText());
                }
                return result;
            } catch (DocumentException e) {
                LOGGER.error("Xml转换异常 >>> 被转换字符串 >>> " + str);
                e.printStackTrace();
            }
        } else {
            return new HashMap<>();
        }
        return null;
    }
 
    /**
     * Map convert Xml string
     * @param params
     * 
     */
    public static String mapToXmlFormatString(Map<String, Object> params) {
        // add xml head
        String head = "<xml>";
        return head + convert(params)+"</xml>";
    }
 
 
    /**
     * 转换
     *
     * @param map
     */
    private static String convert(Map<String, Object> map) {
        // 值类型
 
        // 最后结果标签
        StringBuffer buffer = new StringBuffer();
        for (String key : map.keySet()) {
            // 拼接xml  开头标签
            buffer.append("<" + key + ">");
 
            // 判断value值是否为HashMap类型
            if (map.get(key) instanceof Map) {
                String element = convert((Map<String, Object>) map.get(key));
                buffer.append(element);
            } else {
                buffer.append(map.get(key));
            }
            // 收尾标签
            buffer.append("</" + key + ">");
        }
 
        return buffer.toString();
    }
    
    public static void main(String[] args) {
       System.out.println(xmlFormatStringToMap("<xml><return_code><![CDATA[SUCCESS]]></return_code><id>123</id><nickName>测试</nickName></xml>"));
       Map<String, Object> map=new HashMap<String, Object>();
       map.put("id", 123);
       map.put("nickName", "测试111");
       System.out.println(mapToXmlFormatString(map));
    }
}
